<template>
  <div style="width: 100%;">
    <h2>报修列表</h2>
    <div class="search-bar">
      <el-select v-model="processingStatus" placeholder="请选择处理状态" style="width: 150px;">
        <el-option label="待处理" value="待处理"></el-option>
        <el-option label="处理中" value="处理中"></el-option>
        <el-option label="已完成" value="已完成"></el-option>
      </el-select>
      <el-button @click="fetchRepairs" style="width: 80px;">查询</el-button>
    </div>
    <div v-if="isLoading">加载中···</div>
    <el-table v-else :data="repairList" stripe style="width: 100%">
      <el-table-column prop="id" label="报修id"></el-table-column>
      <el-table-column prop="houseId" label="房屋id"></el-table-column>
      <el-table-column prop="repairContent" label="报修问题描述"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="repairDate" label="期望维修时间"></el-table-column>
      <el-table-column prop="processingStatus" label="报修状态"></el-table-column>
      <el-table-column prop="handlerId" label="处理人员"></el-table-column>
      <el-table-column prop="startDate" label="接受处理时间"></el-table-column>
      <el-table-column prop="completionDate" label="处理完成时间"></el-table-column>
      <el-table-column prop="feedBack" label="维修反馈"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <div style="display: flex; align-items: center;">
            <el-button size="small" v-if="scope.row.processingStatus==='处理中'" @click="openFeedbackDialog(scope.row)">反馈</el-button>
            <el-button size="small" v-if="scope.row.processingStatus==='待处理'" @click="handleRepair(scope.row)">处理</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog v-model="feedbackDialogVisible" title="维修反馈">
      <el-form ref="editFormRef" v-model="feedbackForm">
        <el-form-item label="维修反馈">
          <el-input type="textarea" v-model="feedbackForm.feedback" placeholder="请输入维修反馈"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="feedbackDialogVisible=false">取消</el-button>
        <el-button @click="submitFeedback">提交反馈</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref,onMounted} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
const token=localStorage.getItem("token");
const headers = {
  Authorization: token
};
const isLoading = ref(false);
const repairList=ref([]);
const feedbackDialogVisible = ref(false);
const feedbackForm = ref({
  status:'',
  repairId:null,
  feedback: '' });
const currentFeedbackRepair = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const processingStatus = ref('');
const editFormRef = ref(null);

const dataLoaded = ref(false);
const getRepairList = async () => {
  isLoading.value = true;
  try {
    const response = await axios.get('/api/repair/property/page', {
      headers,
      params: {
        current: currentPage.value,
        size: pageSize.value,
        processingStatus: processingStatus.value
      }
    });
    if (response.data.code === 200) {
      repairList.value = response.data.data.records;
      total.value = response.data.data.total;
      dataLoaded.value = true; // 数据获取成功，设置标志为 true
    } else {
      ElMessage.error('获取报修列表失败')
    }
  } catch (err) {
    ElMessage.error(`获取报修列表失败：${err.message}`)
  } finally {
    isLoading.value = false;
  }
}

const openFeedbackDialog = (row) => {
  if (dataLoaded.value) {
    console.log('openFeedbackDialog方法中传入的row:', row);
    feedbackDialogVisible.value = true;
    currentFeedbackRepair.value = row;
    feedbackForm.value = { feedback: "" };
  } else {
    console.log('数据尚未加载完成，无法打开反馈对话框');
  }
}

const submitFeedback = async () => {
  console.log('进入 submitFeedback 方法');

  // 检查反馈信息是否为空
  if (!String(feedbackForm.value.feedback).trim()) {
    console.log('反馈信息为空，给出警告');
    ElMessage.warning('请输入反馈信息');
    return;
  }

  // 检查 currentFeedbackRepair 是否有值
  if (!currentFeedbackRepair.value ||!currentFeedbackRepair.value.id) {
    console.log('未找到有效的报修记录 ID，给出错误提示');
    ElMessage.error('未找到有效的报修记录 ID');
    return;
  }

  console.log('准备发起更新请求，请求数据：', {
    repairId: currentFeedbackRepair.value.id,
    status: '已完成',
    feedback: feedbackForm.value.feedback
  });

  try {
    const response = await axios.put('/api/repair/property/update',null, {
      headers,params:{
        repairId: currentFeedbackRepair.value.id,
        status: '已完成',
        feedback: feedbackForm.value.feedback
      }});
    console.log('更新请求响应数据：', response.data);

    if (response.data.code === 200) {
      const index = repairList.value.findIndex(
          (item) => item.id === currentFeedbackRepair.value.id
      );

      if (index!== -1) {
        console.log('找到对应的报修记录，更新状态和反馈信息');
        // 保持属性名一致
        repairList.value[index].processingStatus = "已完成";
        repairList.value[index].feedback = feedbackForm.value.feedback;
        repairList.value[index].completionDate = new Date().toISOString();
      } else {
        console.log('未找到对应的报修记录');
      }

      console.log('关闭反馈框，显示成功提示');
      feedbackDialogVisible.value = false;
      ElMessage.success('维修反馈提交成功，标记为已完成');

      console.log('准备重新获取报修列表');
      await getRepairList();
      console.log('报修列表重新获取完成');
    } else {
      console.log('更新请求返回状态码不为 200');
      ElMessage.error('提交反馈失败');
    }
  } catch (err) {
    console.error('更新请求出错：', err);
    ElMessage.error(`提交反馈失败: ${err.message}`);
  }
};
const handleSizeChange = (newSize) => {
  pageSize.value=newSize;
  getRepairList();
}

const handleCurrentChange = (newPage) => {
  currentPage.value=newPage;
  getRepairList();
}

const handleRepair = async (repair) => {
  try{
    const response = await axios.put('/api/repair/property/update',null,
        {headers, params:{repairId: repair.id,status:'处理中',feedback:'已派人处理'
    }});
    if (response.data.code === 200) {
      const index = repairList.value.findIndex(
          (item) => item.id === repair.id
      );
      if (index!== -1) {
        repairList.value[index].handlerId = localStorage.getItem('userId');
        repairList.value[index].startDate = new Date().toISOString();
        repairList.value[index].processingStatus = "处理中";
        repairList.value = [...repairList.value];
      }
      ElMessage.success("已派人处理");
    }else ElMessage.error('处理失败');
  }catch(err){
    ElMessage.error(`处理失败：${err.message}`);
  }
}

const fetchRepairs = () => {
  currentPage.value = 1;
  getRepairList();
}

onMounted(() => {
  getRepairList();
})
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px; /* 可按需调整间距大小 */
}
.el-pagination {
  margin-top: 20px; /* 为页码栏添加顶部间距 */
}
</style>